package com.jcfk.system.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.core.utils.BeanUtils;
import com.jcfk.common.security.utils.SecurityUtils;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.system.dao.RefRolePermissionMappingDao;
import com.jcfk.system.dao.SysPermissionDao;
import com.jcfk.system.domain.dto.SysPermissionDTO;
import com.jcfk.system.domain.po.SysPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

@Service
public class SysPermissionService extends BaseService<SysPermissionDao, SysPermission> {

    @Autowired
    private RefRolePermissionMappingDao refRolePermissionMappingDao;

    /**
     * 根据条件获取用户分页列表
     *
     * @return 返回tree
     */
    public List<SysPermissionDTO> listAll(String enabled) {

        List<SysPermissionDTO> tree = new ArrayList<>();

        QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0).eq(enabled != null, "enabled", enabled).orderByAsc("sort");
        List<SysPermission> list = this.list(queryWrapper);

        List<SysPermissionDTO> permissionDTOS = convertList(list, SysPermissionDTO.class);


        Map<String, List<SysPermissionDTO>> parentChildMap = new HashMap<>();
        // 将节点按照父节点进行分组
        for (SysPermissionDTO node : permissionDTOS) {
            String parentId = node.getParentId();
            parentChildMap.computeIfAbsent(parentId, k -> new ArrayList<>()).add(node);
        }

        // 递归组装树结构
        buildTree(tree, parentChildMap, "0");

        return tree;
    }

    /**
     * 根据条件获取用户分页列表
     *
     * @return 返回tree
     */
    public List<SysPermissionDTO> list(String applicationType,String enabled) {
        QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("deleted", 0)
                .eq(applicationType != null, "application_type", applicationType)
                .eq(enabled != null, "enabled", enabled).orderByAsc("sort");
        List<SysPermission> list = this.list(queryWrapper);

        List<SysPermissionDTO> permissionDTOS = convertList(list, SysPermissionDTO.class);

        return permissionDTOS;
    }

    /**
     * 判断权限Code是否已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(SysPermissionDTO dto) {

        QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("permission_code", dto.getPermissionCode()).eq("deleted", 0);

        if (!StringUtils.isEmpty(dto.getId())) queryWrapper.ne("id", dto.getId());
        Integer count = this.count(queryWrapper);

        if (count > 0) return RetResult.fail("权限Code已存在");

        return RetResult.ok();
    }

    /**
     * 添加权限
     *
     * @param dto
     * @return
     */
    public SysPermissionDTO insert(SysPermissionDTO dto) {

        this.setDefaultValue(dto);
        // 实体
        SysPermission permission = new SysPermission();
        BeanUtils.copyProperties(dto, permission);

        this.save(permission);
        BeanUtils.copyProperties(permission, dto);

        return dto;
    }


    /**
     * 修改权限
     *
     * @param dto
     * @return
     */
    public SysPermissionDTO update(SysPermissionDTO dto) {
        this.setDefaultValue(dto);
        // 实体
        SysPermission permission = new SysPermission();
        BeanUtils.copyProperties(dto, permission);

        this.updateById(permission);
        BeanUtils.copyProperties(permission, dto);

        return dto;
    }


    /**
     * 移动复制权限
     *
     * @param dto
     * @return
     */
    public void move(SysPermissionDTO dto) {

        QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", dto.getId()).eq("deleted", 0);

        // 实体
        SysPermission permission = this.baseMapper.selectOne(queryWrapper);
        if (permission == null) throw new RuntimeException("该权限不存在");

        if (permission.getId() == dto.getParentId()) throw new RuntimeException("自己不能当自己的父级");

        permission.setParentId(dto.getParentId());
        permission.setLastUpdatedUserId(SecurityUtils.getUserId());
        permission.setLastUpdateTime(new Date());
        permission.setLastUpdatedUserName(SecurityUtils.getUserName());

        this.updateById(permission);
    }


    /**
     * 根据条件获取用户分页列表
     *
     * @param tree           树
     * @param parentChildMap 节点集合
     * @param parentId       父id
     */
    private static void buildTree(List<SysPermissionDTO> tree, Map<String, List<SysPermissionDTO>> parentChildMap, String parentId) {
        List<SysPermissionDTO> children = parentChildMap.get(parentId);
        if (children != null) {
            for (SysPermissionDTO child : children) {
                List<SysPermissionDTO> grandchildren = parentChildMap.get(child.getId());
                if (grandchildren != null) {
                    buildTree(child.getChildren(), parentChildMap, child.getId());
                }
                tree.add(child);
            }
        }
    }

    /**
     * 根据主键删除权限(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public RetResult<String> logicDelete(SysPermissionDTO dto) {
        // 判断是否有未删除的 子节点
        QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0).in("parent_id", dto.getIds()).groupBy("parent_id");
        queryWrapper.select("parent_id parentId,count(parent_id) count");
        List<Map<String, Object>> sons = super.listMaps(queryWrapper);
        for (Map<String, Object> son : sons) {
            if (Integer.valueOf(son.get("count").toString()) > 0) {
                return RetResult.fail("请先删除子权限");
            }
        }

        SysPermission permission = new SysPermission();
        permission.setDeleted(1);

        QueryWrapper<SysPermission> deleteWarpper = new QueryWrapper<>();
        deleteWarpper.in("id", dto.getIds());

        this.update(permission, deleteWarpper);

        return RetResult.ok();
    }


    /**
     * 根据主键获取角色信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public SysPermissionDTO get(String id) {
        // 查询数据
        SysPermission item = this.baseMapper.selectById(id);
        SysPermissionDTO dto = new SysPermissionDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        return dto;
    }

    /**
     * 设置添加默认值
     *
     * @param dto 添加对象
     */
    public void setDefaultValue(SysPermissionDTO dto) {
        if (StrUtil.isEmpty(dto.getCreatedUserId())) {
            dto.setCreatedUserId(SecurityUtils.getUserId());
            dto.setCreatedUserName(SecurityUtils.getUserName());
            dto.setCreateTime(new Date());
        }
        dto.setLastUpdatedUserId(SecurityUtils.getUserId());
        dto.setLastUpdateTime(new Date());
        dto.setLastUpdatedUserName(SecurityUtils.getUserName());
        dto.setDeleted(0);
    }

}
